import threading

from mitmproxy import http
from mitmproxy.tools.main import mitmdump
# from threading import Thread
from multiprocessing import Process, Pipe
import multiprocessing

import os


class Cls(object):
    _instance = {"pipe": Pipe()}

    def __init__(self):
        pass

    @classmethod
    def setPipe(cls, pipe):
        cls._instance["pipe"] = pipe
        print(id(cls._instance["pipe"]))

    @classmethod
    def getPipe(cls):
        return cls._instance["pipe"]


def request(flow: http.HTTPFlow):
    # redirect to different host
    # if flow.request.pretty_host == "example.com":
    #     flow.request.host = "mitmproxy.org"
    # # answer from proxy
    # elif flow.request.path.endswith("/brew"):
    #     flow.response = http.Response.make(
    #         418, b"I'm a teapot",
    #     )
    print(id(Cls.getPipe()), multiprocessing.current_process().name, "抓包 {}".format(flow.request.url))
    if "https://apipro.qunjielong.com/activity-biz/activity/detail/frame/chart" == flow.request.url:
        print(flow.request.data)


def run(pipe):
    Cls.setPipe(pipe)
    # print(multiprocessing.current_process().name, os.path.join(os.path.dirname(os.path.abspath(__file__)), "proxy.py"))
    mitmdump(["-s", os.path.join(os.path.dirname(os.path.abspath(__file__)), "proxy.py"), "-p", "8889"])


def runProxy(pipe):
    print(id(pipe))
    task = Process(target=run, args=(pipe, ))
    task.daemon = True
    task.start()

